module key(
    input   wire                clk,
    input   wire                rst,
    input   wire    [3:0]       key_in,
    output    reg [3:0]   key_val
  );

  //10ms
  parameter MS_MAX = 20'd499_000;


  parameter IDLE = 0;
  parameter PRASS = 1;
  parameter RELEASE = 2;
  reg [19:0]  ms_count;
  reg [1:0]   key_state;
  //
  always@(posedge clk or posedge rst)
  begin
    if(rst)
      ms_count <= 0;
    else
    begin
      if(ms_count == MS_MAX)
        ms_count <= 0;
      else
        ms_count = ms_count + 1;
    end
  end

  //
  always@(posedge clk or posedge rst)
    if(rst)
    begin
      key_state <= IDLE;
      key_val <= 0;
    end
    else if (key_val == 0)
    begin
      if(ms_count == MS_MAX)
      begin
        if(key_state == IDLE)
        begin
          if(key_in != 4'hf)
          begin
            key_state <= PRASS;
          end
        end
        else if(key_state <= PRASS)
        begin
          case (key_in)
            4'b1110:
            begin
              key_val <= 4'd1;
              key_state <= RELEASE;
            end
            4'b1101:
            begin
              key_val <= 4'd2;
              key_state <= RELEASE;
            end
            4'b1011:
            begin
              key_val <= 4'd3;
              key_state <= RELEASE;
            end
            4'b0111:
            begin
              key_val <= 4'd4;
              key_state <= RELEASE;
            end
            default:
            begin
              key_val <= key_val;
              key_state <= IDLE;
            end
          endcase
        end
        else if(key_in == 4'hf)
        begin
          key_state <= IDLE;
          key_val <= 0;
        end
      end
    end
    else
      key_val <= 0;

endmodule
